<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="180" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span v-if="scope.row.state === 0" style="color: green">启用</span>
					<span v-else-if="scope.row.state === -1" style="color: red">禁用</span>
					<span v-else="scope.row == 0" style="color: grey">未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="120" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="上级部门" width="150" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="currentPage"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--
			:visible.sync：控制是否显示模态框，true显示，false不显示
			:rules：绑定一个表单验证规则
			ref：给表单取一个别名
			prop：表单验证名称
		-->
		<!--新增/编辑界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员">
					<el-select v-model="saveForm.manager" value-key="id" placeholder="请开始你的表演">
						<!--
							:key---唯一表示符
							:label---下拉选项框中从服务端获取到的值
							:value---返回给模型层的数据
							item---迭代得到的对象(如果要向模型层返回对象，则需要在) el-select必须在标签中添加value-key，值为唯一表示符
						-->
						<el-option
								v-for="item in employees"
								:key="item.value"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phoneSELECT}}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级部门">
					<el-cascader
							v-model="saveForm.department"
							:options="tree"
							:props="{ checkStrictly: true,
							 		value:'id',
							 		label:'name'
							 }"
							clearable></el-cascader>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
                title:"",
                filters: {
					keyword: ''
				},
				departments: [],
				employees:[],
				tree:[],
				total: 0,
                currentPage: 1,
                pageSize: 10,
				listLoading: false,
				sels: [],//列表选中列

				saveFormVisible: false,//新增界面是否显示
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ]
				},
				// 新增界面数据
				saveForm: { // 置空表单数据
                    id: null, // 新增时id为空
					name: '',
					sn: '',
					state: 0, // 默认为启用
					manager: null,
					department: null
				}

			}
		},
		methods: {
		    search(){ // 高级查询，一定定位到第一页
		        this.currentPage = 1;
		        this.getDepartments();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			// 获取一二级部门
			getTree(){
		      this.$http.post("/dept/tree")
				  .then(result=>{
				      this.tree = result.data;
				  })
			},
			// 获取员工信息
			getEmployees(){
		        this.$http.get("/employee/list")
					.then(result=>{
						this.employees = result.data;
					})
					.catch(result=>{

					})
			},
			// 获取部门列表
			getDepartments() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword,
                };
                this.listLoading = true; // 开启忙等框
                // 使用axios向后端localhost:8080发送请求，拿数据
                this.$http.post("/dept/page", para)
                    .then(result => {
                        this.listLoading = false; // 关闭忙等框
                        result = result.data;
                        this.departments = result.rows;
                        this.total = result.total;
                    })
                    .catch(result => { // 操作失败时，向前端返回信息提示
                        console.log(result);
                        this.$message({
                            type: 'error',
                            message: `系统繁忙，程序猿正在快马加鞭的赶来！`
                        });
                    });
            },
				//NProgress.start();
				/*getDepartmentListPage(para).then((res) => {
					this.total = res.data.total;
					this.departments = res.data.departments;
					this.listLoading = false;
					//NProgress.done();
				});
			},*/
			// 删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true; // 开启忙等框
					//NProgress.start();
					// 向端发送delete请求，传递id删除数据
					this.$http.delete("/dept/" + row.id)
						.then(result=>{
						    result = result.data;
                            this.listLoading = false;
                            if(result.success){
                                this.$message({
                                    type: 'success',
                                    message: result.message
                                });
                                this.currentPage = 1;
                                // 删除成功，刷新页面
                                this.getDepartments();
							} else {
                                this.$message({
                                    type: 'error',
                                    message: result.message
                                });
							}
						})
						.catch(result=>{
                            this.listLoading = false;
                            console.log(result);
                            this.$message({
                                type: 'error',
                                message: result.message
                            });
						})
				})
            },
            // 显示编辑界面
			handleEdit: function (index, row) {
                this.getTree();
                this.title = "编辑";
                this.saveFormVisible = true;
                this.saveForm = Object.assign({}, row); // 克隆当前行数据并回显
                // 如果dirPath不为空w才做上级部门回显
                if(row.dirPath){
                    let arr = row.dirPath.split("/"); // 以 / 作为分隔符，得到一个String类型数组
                    let arr1 = [];
                    for(let i=1; i<arr.length-1; i++){
                        arr1.push(parseInt(arr[i])); // parseInt将String转化为int
                    }
                    this.saveForm.department = arr1;
                }
                this.$refs['saveForm'].resetFields(); // 置空表单校验
			},
			//显示新增界面
			handleAdd: function () {
			    this.getTree();
			    this.title = "新增";
				this.saveFormVisible = true;
				this.saveForm = { // 置空表单数据
                    id: null, // 新增时id为空
                    name: '',
                    sn: '',
                    state: 0, // 默认为启用
                    manager: null,
                    department: null,
				};
				this.$refs['saveForm'].resetFields();
			},
			// 新增或编辑
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => { // 校验表单
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true; // 开启提交按钮忙等框
							// NProgress.start();
							let para = Object.assign({}, this.saveForm); // 这里是克隆表单信息
							// 格式化信息
							if(para.department){
							    para.department = {"id":para.department[para.department.length-1]};
							}
							// 使用axios向后端发送post请求，进行新增或修改操作
							this.$http.post("/dept/addOrUpdate", para) // 将表单信息传递给后台
								.then(result=>{
								    result = result.data;
                                    if(result.success){
                                        this.$message({
                                            type: 'success',
                                            message: result.message
                                        });
                                        // 刷新页面
                                        this.$refs['saveForm'].resetFields(); // 重置表单校验
                                        this.saveFormVisible = false; // 关闭模态框
                                        this.getDepartments();
									}else {
                                        this.$message({
                                            type: 'error',
                                            message: result.message
                                        });
									}
								})
								.catch(result=>{
                                    this.editLoading = false; // 关闭模态框
									console.log(result);
                                    this.$message({
                                        type: 'error',
                                        message: result.message
                                    });
								})
							/*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id); // .toString(); 在后端接收的数据为对象，不需要转换为字符串
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { ids: ids }; ids本身就是一个对象，不需要再封装为一个对象了
					this.$http.patch("/dept",ids)
						.then(result=>{
                            this.listLoading = false;
                            result = result.data;
                            if(result.success){
                                this.$message({
                                    type: 'success',
                                    message: result.message
                                });
                                // 删除成功刷新页面
								this.currentPage=1;
								this.getDepartments();
							}else {
                                this.$message({
                                    type: 'error',
                                    message: result.message
                                });
							}
						})
						.catch(result=>{
                            this.listLoading = false;
                            this.$message({
                                type: 'error',
                                message: result.message
                            });
						})
				})
			}
		},
		mounted() {
			this.getDepartments();
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>